package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.OrderSettingListDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.Setmeal;
import com.itheima.service.OrderSettingListService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.itheima.pojo.Order.*;

@Service(interfaceClass = OrderSettingListService.class)
@Transactional
public class OrderSettingListServiceImpl implements OrderSettingListService{
    @Autowired
    private OrderSettingListDao orderSettingListDao;
    /**
     * 分页查询预约订单
     * @param map
     * @return
     */
    @Override
    public PageResult findPage(Map map) {
        /*判断传入的变量是否为null*/
        if (map == null){
            return new PageResult(null,null);
        }
        /*不为null的前提下，获取传入的数据*/
        /*Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();*/
        /*当前页*/
        Integer currentPage = (Integer) map.get("currentPage");
        /*一页显示的条数*/
        Integer pageSize = (Integer) map.get("pageSize");

        /*查询条件*/
        Map query = (Map) map.get("query");

        try {
            /*queryDate*/
            List queryDate = (List) query.get("queryDate");
            /*queryStatus*/
            String queryStatus = (String) query.get("queryStatus");
            /*queryType*/
            String queryType = (String) query.get("queryType");
            /*queryString*/
            String queryString = (String) query.get("queryString");
            /*无查询条件的普通查询*/
            if (queryDate == null && queryStatus == null && queryType == null && queryString == null){
                /*PageHelper.startPage(currentPage,pageSize);
                List<Order> orderList = orderSettingListDao.findAll();
                OrderListFactory(orderList);
                PageInfo<Order> orderPageInfo = new PageInfo<>(orderList);*/
                PageInfo<Order> orderPageInfo = findAllFactory(currentPage, pageSize, null, null, null, null, null);
                return new PageResult(orderPageInfo.getTotal(),orderPageInfo.getList());
            }else {
                /*有预约条件的复杂查询*/
                String startDate = null;
                String endDate = null;
                if (queryDate != null){
                    startDate = (String) queryDate.get(0);
                    endDate = (String) queryDate.get(1);
                }
                //如果queryString是会员名
                Member memberByName = orderSettingListDao.findMemberByName(queryString);
                //如果queryString是手机号
                Member memberByPhoneNumber = orderSettingListDao.findMemberByPhoneNumber(queryString);
                //根据会员名或者手机号查找对应的memberId
                Integer memberId = null;
                if (memberByName != null){
                    memberId = memberByName.getId();
                } else if (memberByPhoneNumber != null){
                    memberId = memberByPhoneNumber.getId();
                }

                PageInfo<Order> orderPageInfo = findAllFactory(currentPage, pageSize, startDate, endDate, queryStatus, queryType, memberId);
                return new PageResult(orderPageInfo.getTotal(),orderPageInfo.getList());
                /*if (queryDate != null && queryStatus == null && queryType == null && queryString == null){
                    PageHelper.startPage(currentPage,pageSize);
                    List<Order> orderList = orderSettingListDao.findAll(startDate,endDate);
                    OrderListFactory(orderList);
                    PageInfo<Order> orderPageInfo = new PageInfo<>(orderList);
                    return new PageResult(orderPageInfo.getTotal(),orderPageInfo.getList());
                }*/
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResult(null,null);
        }
    }

    /**
     * 为新增预约查找所有套餐信息
     * @return
     */
    @Override
    public Result findAllSetMeal() {

        try {
            List<Setmeal> setMealList = orderSettingListDao.findAllSetMeal();
            if (setMealList == null){
                return new Result(false, MessageConstant.QUERY_SETMEALLIST_FAIL);
            }
            return new Result(true,MessageConstant.QUERY_SETMEALLIST_SUCCESS,setMealList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEALLIST_FAIL);
        }
    }

    /**
     * 新增预约
     * @param map
     * @return
     */
    @Override
    public Result add(Map map) {
        if (map == null){
            return new Result(false,MessageConstant.ADD_ORDER_FAIL);
        }

        try {
            String phoneNumber = (String) map.get("phoneNumber");
            String name = (String) map.get("name");
            Integer setmealId = (Integer) map.get("setmealId");


            String orderDate = (String) map.get("orderDate");
            int t = orderDate.indexOf("T");
            String substring = orderDate.substring(0,t);
            /*根据手机号判断会员是否已存在*/
            Member member = orderSettingListDao.findMemberByPhoneNumber(phoneNumber);
            if (member == null){
                /*用户未注册，智能注册*/
                member = new Member();
                member.setRegTime(new Date());
                member.setId(0);
                member.setName(name);
                member.setPhoneNumber(phoneNumber);
                boolean flag = orderSettingListDao.addMember(member);
                if (!flag){
                    return new Result(false,MessageConstant.ADD_ORDER_FAIL);
                }
            }
            if (!name.equals(member.getName())){
                return new Result(false,"该手机号已注册，请重试");
            }
            /*在用户已存在的前提下，新增order*/
            member = orderSettingListDao.findMemberByPhoneNumber(member.getPhoneNumber());

            Order order = new Order();
            order.setSetmealId(setmealId);
            order.setMemberId(member.getId());
            order.setOrderStatus(ORDERSTATUS_NO);
            order.setOrderType(ORDERTYPE_TELEPHONE);
            order.setOrderDate(DateUtils.parseString2Date(substring));
            orderSettingListDao.addOrder(order);
            return new Result(true,MessageConstant.ADD_ORDER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_ORDER_FAIL);
        }
    }

    /**
     * 根据setmealId查找setmeal
     * @param setmealId
     * @return
     */
    @Override
    public Result findSetmealById(Integer setmealId) {
        if (setmealId == null){
            return new Result(false,MessageConstant.QUERY_SETMEALLIST_FAIL);
        }

        try {
            List<Setmeal> setmealList = new ArrayList<>();
            Setmeal setmeal = orderSettingListDao.findSetmealById(setmealId);
            setmealList.add(setmeal);
            return new Result(true,MessageConstant.QUERY_SETMEALLIST_SUCCESS,setmeal);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_SETMEALLIST_FAIL);
        }
    }

    /**
     * 修改order
     * @param map
     * @return
     */
    @Override
    public Result edit(Map map) {
        if (map == null){
            return new Result(false,MessageConstant.EDIT_ORDER_FAIL);
        }

        try {
            //orderId
            Integer orderId = (Integer) map.get("orderId");
            //name
            String name = (String) map.get("name");
            //setmealId
            Integer setmealId = (Integer) map.get("setmealId");
            //orderDate
            String orderDateStr = (String) map.get("orderDate");
            /*int t = orderDateStr.indexOf("T");
            String substring = orderDateStr.substring(0,t);*/
            Date orderDate = DateUtils.parseString2Date(orderDateStr);
            //orderStatus
            String orderStatus = (String) map.get("orderStatus");
            //orderType
            String orderType = (String) map.get("orderType");

            /*创建order对象*/
            Order order = new Order();
            order.setId(orderId);
            order.setSetmealId(setmealId);
            order.setOrderDate(orderDate);
            if ("已到诊".equals(orderStatus)){
                order.setOrderStatus(ORDERSTATUS_YES);
            }else order.setOrderStatus(ORDERSTATUS_NO);
            order.setOrderType(orderType);

            orderSettingListDao.editOrderByOrderId(order);
            return new Result(true,MessageConstant.EDIT_ORDER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.EDIT_ORDER_FAIL);
        }
    }

    /**
     * 删除指定order
     * @param id
     * @return
     */
    @Override
    public Result delete(Integer id) {
        if (id == null){
            return new Result(false,MessageConstant.DELETE_ORDER_FAIL);
        }

        try {
            orderSettingListDao.deleteOrderById(id);
            return new Result(true,MessageConstant.DELETE_ORDER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_ORDER_FAIL);
        }
    }

    /**
     * switch发生变动时修改
     * @param order
     * @return
     */
    @Override
    public Result editOrderStatus(Order order) {
        if (order == null){
            return new Result(false,"改变状态失败");
        }

        try {
            if (order.isStatus()){
                order.setOrderStatus(ORDERSTATUS_YES);
                orderSettingListDao.editOrderStatus(order);
            }else {
                order.setOrderStatus(ORDERSTATUS_NO);
                orderSettingListDao.editOrderStatus(order);
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Order> OrderListFactory(List<Order> orderList){
        for (Order order : orderList) {
            String orderStatus = order.getOrderStatus();
            if ("已到诊".equals(orderStatus)){
                order.setStatus(true);
            }else order.setStatus(false);
            Integer memberId = order.getMemberId();
            Member memberById = orderSettingListDao.findMemberById(memberId);
            String memberString = JSON.toJSONString(memberById, SerializerFeature.DisableCircularReferenceDetect);
            Member newMember = JSONArray.parseObject(memberString, Member.class);
            order.setMember(newMember);
            Integer setmealId = order.getSetmealId();
            Setmeal setmeal = orderSettingListDao.findSetmealById(setmealId);
            String setmealString = JSON.toJSONString(setmeal, SerializerFeature.DisableCircularReferenceDetect);
            Setmeal newSetmeal = JSONArray.parseObject(setmealString, Setmeal.class);
            order.setSetmeal(newSetmeal);
        }
        return orderList;
    }

    public PageInfo<Order> findAllFactory(Integer currentPage,Integer pageSize,String startDate,String endDate,String queryStatus,String queryType,Integer memberId){
        PageHelper.startPage(currentPage,pageSize);
        List<Order> orderList = orderSettingListDao.findAll(startDate,endDate,queryStatus,queryType,memberId);
        List<Order> newOrderList = new ArrayList<>();
        for (Order order : orderList) {
            String orderString = JSON.toJSONString(order, SerializerFeature.DisableCircularReferenceDetect);
            Order newOrder = JSONArray.parseObject(orderString, Order.class);
            newOrderList.add(newOrder);
        }
        OrderListFactory(newOrderList);
        PageInfo<Order> orderPageInfo = new PageInfo<>(newOrderList);
        return orderPageInfo;
    }
}
